//
//  UserProfileViewModel.swift
//  GithubUserSet
//
//  Created by Golden Jellyfish on 2025/9/2.
//

import Foundation

struct GithubUser: Codable {
    let name: String
    let bio: String?
}

enum LoadingState<Value> {
    case loading
    case success(Value)
    case failure(Error)
}

@MainActor
class UserProfileViewModel: ObservableObject {
    
    @Published var state: LoadingState<GithubUser> = .loading
    
    func fetchUser(username: String) async {
        self.state = .loading
        
        do {
            guard let url = URL(string: "https://api.github.com/users/\(username)") else {
                throw URLError(.badURL)
            }
            let (data, _) = try await URLSession.shared.data(from: url)
            let user = try JSONDecoder().decode(GithubUser.self, from: data)
            self.state = .success(user)
            
        } catch {
            print("Error fetching user: \(error)")
            self.state = .failure(error)
        }
    }
    
    @Published var name: String = "SwiftUI 大师"
    @Published var bio: String = "一位经验丰富的 iOS 开发者，正在探索声明式 UI 的奥秘。"
    @Published var isFollowing: Bool = false
    
    func toggleFollowStatus() {
        isFollowing.toggle()
    }
}
